﻿using System;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace Sunny.Util
{
    public class IpHelper
    {
        /// <summary>
        /// 获取ip对应的地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string GetLocationByIp(string ip)
        {
            string location = "未知IP";
            if(IsInternalIp(ip))
            {
                location = "本地IP";
            }
            else
            {
                try
                {
                    HttpClient httpClient = new HttpClient();
                    var result = httpClient.GetStringAsync($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").Result;
                    if(!string.IsNullOrEmpty(result))
                    {
                        JObject jObject = JObject.Parse(result);
                        location = jObject["pro"].ToString() + " "+jObject["city"].ToString();
                    }
                }
                catch (System.Exception e)
                {
                    
                }
            }
            return location;
        }
        
        public static bool IsInternalIp(string ip)
        {
            return "127.0.0.1".Equals(ip,StringComparison.OrdinalIgnoreCase) || "::1".Equals(ip,StringComparison.OrdinalIgnoreCase);
        }
    }
}